package org.example.c_0_003;

import org.junit.Test;

import java.util.ArrayList;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock示例
 */
public class T_ReentrantLock {
    private int count0 = 0;
    private ReentrantLock lock = new ReentrantLock();
    // 构造参数传 true 则是公平锁
//    private ReentrantLock lock = new ReentrantLock(true);
    private void m(){
        for (int i = 0; i < 100000; i++) {
            try{
                lock.lock();
                count0++;
            }finally {
                lock.unlock();
            }
//            synchronized (this){
//                count0++;
//            }
        }
    }

    @Test
    public void run(){
        long start = System.currentTimeMillis();
        ArrayList<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            threads.add(new Thread(this::m));
        }
        threads.forEach(thread -> thread.start());

        threads.forEach(thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("结果："+count0+"   用时："+(System.currentTimeMillis()-start));
    }
}
